//添加商品规格
import { reactive,ref,UnwrapRef,nextTick,watch} from "vue";
import { message } from 'ant-design-vue';

export class SukList {
    constructor() {
      //parameters
    }

   /**
    * 默认属性
    */
    public data=reactive({
            suklist:[{
                id:0,//规格项ID
                name:undefined,
                eName:undefined,
                indeterminate:false,//设置 indeterminate 状态，只负责样式控制--false为全选样式-true有选择
                checkAll:false, //全选控制--true为全选---false为空
                valueList:[],//默认值{value:32,checked:true},{value:33,checked:true},{value:34,checked:true}
                sukNam:[//规格项
                    {name:"尺码",eName:"cima",checked:true},
                    {name:"颜色",eName:"colour",checked:true},
                    {name:"时间",eName:"time",checked:true},
                    {name:"功效",eName:"effect",checked:true},
                    {name:"成价",eName:"component",checked:true},
                    {name:"度数",eName:"degrees",checked:true},
                    {name:"适用人",eName:"renmin",checked:true}],
                }],
            addColumns:[],//缓存数据的添加数表格数据
            columns:[],    
            columnsDefault: [{
                title: '库存数量',
                dataIndex: 'stockNum',
                key: 'stockNum',
                slots: { customRender: 'stockNum' },
              },{
                title: '库存预警数量',
                dataIndex: 'stockNumWarning',
                key: 'stockNumWarning',
                slots: { customRender: 'stockNumWarning' },
              },{
                title: '销售单价',
                dataIndex: 'price',
                key: 'price',
                slots: { customRender: 'price' },
              },{
                title: '划线价',
                dataIndex: 'passPrice',
                key: 'passPrice',
                slots: { customRender: 'passPrice' },
              },{
                title: '体积',
                dataIndex: 'volume',
                key: 'volume',
                slots: { customRender: 'volume' },
                
              },{
                title: '重量',
                dataIndex: 'weight',
                key: 'weight',
                slots: { customRender: 'weight' },
              }, {
                title: '默认显示',
                dataIndex: 'isdefault',
                key: 'isdefault',
                slots: { customRender: 'isdefault' },
              }, {
                title: '状态',
                dataIndex: 'state',
                key: 'state',
                slots: { customRender: 'state' },
              },{
                title: '规格主图',
                dataIndex: 'skuImgs',
                key: 'skuImgs',
                width:130,
                slots: { customRender: 'skuImgs' }
              },{
                title:'操作',
                dataIndex: 'action',
                key:'action',
                fixed: 'right',
                width:120,
                slots: { customRender: 'action' },
              }],
            cols:["name", "passPrice", "price", "stockNum", "stockNumWarning", "volume", "weight", "isdefault", "state"], //可编辑字段 
            skuInfo:[],//SKU信息
            skuInfoCache:[] //原数据-修改数据
       })

     /**
      * 添加规格
      * @param index 
      */
     public sukAdd(index:number){
          this.data.suklist.push(this.data.suklist[0]);
          var arryNew = JSON.parse(JSON.stringify(this.data.suklist));//处理引用类型数据赋值问题
              arryNew[index].id = index;
              arryNew[index].name= undefined;
              arryNew[index].eName= undefined;
              arryNew[index].value=[]     //默认值--可以通过ajax获取
              arryNew[index].valueList=[] //默认值--可以通过ajax获取
              this.data.suklist = arryNew;
      }
     
     /**
      * 获取规格信息--添加部信息
      * @param obj 
      * @param index 
      */ 
     public onSelect(obj:Object,index:number){
        this.data.suklist[index].name=obj['name'];
        this.data.suklist[index].eName=obj['eName'];
        for(let i=0;i<this.data.suklist.length;i++){//规格涮选
          for(let j=0;j<this.data.suklist[i].sukNam.length;j++){
            this.data.suklist[i].sukNam[j].checked=true;
            if(this.data.suklist[i].sukNam[j].name===obj['name']){
              this.data.suklist[i].sukNam[j].checked=false;
            }
          }
        }
        this.data.addColumns[index]={ //添加头部信息
              title:obj['name'],
              dataIndex:obj['eName'],
              key:obj['eName'],
              slots: { customRender:obj['eName']}
            }
     }
     /**
      * 删除规格项
      * @param index 
      */
     public sukRemove(index:number){
         this.data.suklist.splice(index,1);//删除规格项
         this.data.columns.splice(index,1);//删除表格数据
         delete this.data.columns[0]['customRender']; 
     }

     /**
      * //新增规格值
      * @param index 
      */
     public addSukValue(index:number){ 
        let objs={
            value:'',
            checked:false
          }  
        this.data.suklist[index].valueList.push(objs);
        let obj = {}; 
        this.data.suklist[index].valueList = this.data.suklist[index].valueList.reduce(function(item, next){ //对像去重处理
         obj[next.value] ? '' : obj[next.value] = true && item.push(next);
         return item;
       },[]);

    } 

    /**
     * //删除规格值
     * @param index 
     * @param key 
     * @param itme 
     */
    public onDel(index:number,key:number){
      let rule1=this.data.suklist[0].valueList;
      let rule2=this.data.suklist[1]?this.data.suklist[1].valueList : [];

      if(!index && rule1.length<=1 && rule2.length>0){
         message.info('规格2有值不能删除')
      }else{
        this.data.suklist[index].valueList.splice(key,1);//删除规格值
        this.delSukInfo(index,key)//删除表格数据 
      }

    }

    /**
     * //点击规格值全选
     * @param e 
     * @param index 
     */
    public onCheckAllChange(e: any,index:number){ 
      let state=this.data.suklist[index]; 
      let valueList=state.valueList
          valueList.forEach(element=>{
            if(e.target.checked){
              element.checked=true
            }else{
              element.checked=false
            }
          }) 
       if(e.target.checked){
         this.data.suklist[index].sukNam.forEach(item =>{
            if(!item.checked){
              this.onSelect(item,index);   
            }
         })
        
       } 
        
       this.addTablSuk(index,state); //重新生成数据
       
    }

    /**
     * 输入框失去焦点-添加数据
     * @param e 
     * @param index 
     * @param key 
     */
    public onBlur(e:any,index:number,key:number){ 
      let state=this.data.suklist[index];
      let valueList=state.valueList;
      if(e.target.value && !e.target.checked){
          valueList[key].checked=true; //选择
          this.addTablSuk(index,state);//添加
       }else{
        valueList[key].checked=false; //选择
        this.delSukInfo(index,key)
       }
       this.allCheckBox(state,valueList)
    }

    /**
     * 深度监听规格选择值的变化
     * @param e 
     * @param index 
     * @param key 
     */

    public onCheckBox(e: any,index:number,key:number){ 
        let state=this.data.suklist[index];
        let valueList=state.valueList;
        this.allCheckBox(state,valueList);
        if(e.target.checked && valueList[key].value){ 
           this.addTablSuk(index,state) //添加信息
        }else{
           this.delSukInfo(index,key) //删除
        }
    }
     
   /**
    * 处理全选样式方法
    * @param state 
    * @param valueList 
    */
    public allCheckBox(state:any,valueList:any){ 
        let newArr=[];
        valueList.forEach(element=>{ //处理全选
              if(element.checked){ //全选
                newArr.push(element.checked);
              }
         })
         if(newArr.length<=0){
          console.log("全不选")
          state.indeterminate=false
          state.checkAll=false
         }else if(newArr.length==valueList.length){
          console.log("全选~~~~~~~~~~")
          state.indeterminate=false
          state.checkAll=true 
         }else{
          console.log("只选一个~~~~~~~~~~~~~~~~~~~~")
          state.indeterminate=true
          state.checkAll=false
         }
     } 

   /**
    * 获取信息选择的信息个数
    * @param index 
    */
   public runNewArr(index:number){
        if(!this.data.suklist[index]) return []; //没有数据返空
        let rule1=this.data.suklist[index].valueList;
        let newArr1 = rule1.filter(item=> { //过滤数据
            return item.value && item.checked;
        })
        return newArr1;
   }
  
     /**
    * 生成表格数据
    * @param index
    */ 
   public addTablSuk(index:number,state:any){ //统一地方处理表格数据
          let newArr1 = this.runNewArr(0);
          let newArr2 = this.runNewArr(1);
          let eName2=newArr2.length>0?this.data.suklist[1].eName:"";
          let eName1=this.data.suklist[0].eName;
        this.addTablHead(index,state,newArr1,newArr2); //处理表格头
        this.data.skuInfo=[];//1.清空数据重新生成
        if(newArr1.length<=0 && newArr2.length>0){
          for(let i=0;i<newArr2.length;i++){
            this.sukInfoData(newArr1,eName1,newArr2,eName2,i,i,1)
          }
        }
        for(let i=0;i<newArr1.length;i++){ //这个算法是没有问题的
          if(newArr2.length>0){
              for(let j=0;j<newArr2.length; j++){ //3个数据
                this.sukInfoData(newArr1,eName1,newArr2,eName2,i,j,1)
              }
          }else{
             this.sukInfoData(newArr1,eName1,newArr2,eName2,i,i,0)
          }
        }

      this.getSkuInfo(eName1,eName2);//最后结果数据处理
       
    }

    /**
     * 结果数据处理
     */
    public getSkuInfo(eName1:any,eName2:any){
      console.log(eName1,'=================eName1================')
      console.log(eName2,'=================eName2================')
      console.log(this.data.skuInfo,'============skuInfo===============')
      console.log(this.data.skuInfoCache,'============数据是多少===============')
      //1.del和del2相等就是同一个数据
      //存在的数据没有就取自己的
      let newArr=[];
      let cacheArr=this.data.skuInfoCache;
      this.data.skuInfo.forEach((res,index)=>{
         if(cacheArr[index]){
           if(cacheArr[index].del==res.del && cacheArr[index].del2==res.del2){

             if(cacheArr[index][eName1]!=res[eName1]){ 
               cacheArr[index][eName1]=res[eName1]
             }
             if(cacheArr[index][eName2]!=res[eName2]){
               cacheArr[index][eName2]=res[eName2]
             }
             newArr.push(cacheArr[index])
           }else{
             newArr.push(res)
           }
         }else{
            newArr.push(res)
          }
      })
      console.log(newArr,'----------------最后的结果-----------------')
      this.data.skuInfo=newArr;
    }
   
    /**
     * 重新生成头部
     * @param index 
     * @param state
     */
    public addTablHead(index:number,state:any,newArr1:any,newArr2:any){
           this.data.columns=this.data.columnsDefault;//重置数据
       let arr=this.data.addColumns.concat(this.data.columns); //合并数据
           this.data.columns=arr;
         
         if(newArr1.length<=0){
            this.data.columns.splice(0,1);//删除表格数据
          }  
         if(newArr2.length<=1){
              delete this.data.columns[0]['customRender'];         
              if(newArr2.length<=0){
                this.data.columns.splice(1,1);//删除表格数据
              }
          }

         if(newArr1.length<=0 && newArr2.length<=0){ //没有数据置空
            this.data.columns=[]
          }
        if(newArr2.length>1 && newArr1.length>1){ //有多条数据处理表格合并
            this.render(newArr1,newArr2);
          } 
          this.editCols(state)   
    }

   /**
    * 处理插入的数据
    * del,del2,key,keys参数不能删除
    * @param rule1 
    * @param eName1 
    * @param rule2 
    * @param eName2 
    * @param i 
    * @param j 
    */
   public sukInfoData(rule1:any,eName1:string,rule2:any,eName2:string,i:number,j:number,index:number){
          let info={
            del:i,//0, //1-- 
            del2:j, //0,1, ---2
            key:i+'_'+j,
            keys:index,
            id:'00000000000',
            passPrice: 0,
            price: 0,
            skuImgs: "",
            state:0,
            stockNum: 1,
            stockNumWarning: 1,
            volume: 0,
            weight: 0,
            isdefault: 0,
            degrees:"0",
         }
         if(rule1.length>0){
          info[eName1]=rule1[i].value
         }
         if(rule2.length>0){
          info[eName2]=rule2[j].value
        }
        this.data.skuInfo.push(info);
   }

   /**
    * 处理数据表格例合并
    * @param rule1 
    * @param rule2 
    */
   public render(rule1:any,rule2:any){
    this.data.columns[0]["customRender"]=({ text,index }) => {      
        let newArr1 = rule1.filter(item=> { //过滤数据
            return item.value && item.checked;
        })
        let newArr2 = rule2.filter(item=> { //过滤数据
            return item.value && item.checked;
        })
        const obj = {
          children: text,
          props: {} as any,
        };
        obj.props.rowSpan = 0;
        for(let i=0;i<newArr1.length;i++){ //处理合并1--
          if(index==newArr2.length*i){
            obj.props.rowSpan = newArr2.length;
          }
        }
        return obj;
      }
   }
    /**
     * //处理可编辑字段
     * @param state 
     */
    public editCols(state:any){ 
      for(let i=0;i<this.data.cols.length;i++){
        if(this.data.cols !=state.eName){
          this.data.cols.push(state.eName);
          break
        }
      }
      let Arr=new Set(this.data.cols);
      this.data.cols=[...Arr];
    }
    
    /**
     * //删除表格数据
     * @param index 
     * @param key 
     */
    public delSukInfo(index:number,key:number){ 
           if(this.data.suklist[1]){
              let newArr2 = this.runNewArr(1);
                if(newArr2.length<=1){
                  delete this.data.columns[0]['customRender']; 
                }
                if(newArr2.length<=0){
                  return this.sukRemove(index)//删除信息
                } 
            }
         
         //重新生成一个数组
         let newArr=[] 
         let Arr=this.data.skuInfo;
             Arr.forEach((res,i)=>{
                if(index==0 && res.del!=key) {
                  newArr.push(res)
                }
                if(index==1 && res.del2!=key){
                  newArr.push(res)
                }
            })
         this.data.skuInfo=newArr;
     }
   
}


export const sukClass= new SukList();